package com.chookss.home.audit;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.home.audit.clockIn.ClockInAskHolidayActivity;
import com.chookss.home.audit.adapter.ClockInHolidayRecordAdapter;
import com.chookss.home.audit.adapter.ReimbursementRecordAdapter;
import com.chookss.home.audit.seal.SealHomeActivity;
import com.chookss.home.audit.seal.SealRecordAdapter;
import com.chookss.home.audit.reimbursement.ReimbursementActivity;
import com.chookss.home.entity.HolidayDetailEntity;
import com.chookss.home.entity.ReimbursementDetailEntity;
import com.chookss.home.entity.WorkNewEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

public class MyAuditRecordActivity extends BaseAct {
//已审批列表

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    private BaseQuickAdapter adapter;
    private List<WorkNewEntity> list = new ArrayList<>();
    private List<WorkNewEntity> cacheList = new ArrayList<>();
    private List<HolidayDetailEntity> cacheHolidayList = new ArrayList<>();
    private List<ReimbursementDetailEntity> cacheReimbursementList = new ArrayList<>();
    private int type = 4; // 1新闻2视频3补卡4-请假5-外勤6图文7报销8物料9借款10补贴11用章12维修13交付14离职15晋升16回款17修改项目金额18入职19加班
    private int currentPage = 1;
    private int pageSize = 20;
    private boolean isEnd = false;//是否到底
    private View emptyView;
    private TextView tvNone;//空布局;
    private String groupCode="";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_srlview_top);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 4);
        groupCode=getIntent().getStringExtra("groupCode");
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) smrRf.getLayoutParams();
        params.setMargins(0, Utils.dip2px(this, 12), 0, 0);
        smrRf.setLayoutParams(params);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        if (type == 7||type == 9||type == 10||type == 16) {
            adapter = new ReimbursementRecordAdapter(R.layout.item_reimbursement_record, this, list,type);
        }else if (type == 11) {
            adapter = new SealRecordAdapter(R.layout.item_seal_record, this, list);
        }else {
            adapter = new ClockInHolidayRecordAdapter(R.layout.item_clock_holiday_record, this, list);
        }
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        recyclerView.setAdapter(adapter);
        emptyView = LayoutInflater.from(this).inflate(R.layout.layout_common_empty, recyclerView, false);
        tvNone = emptyView.findViewById(R.id.tvEmpty);
        if (type == 7) {
            commonTitleTxt.setText("报销记录");
            tvNone.setText("暂无报销记录");
        } else if (type == 9) {
            commonTitleTxt.setText("借款记录");
            tvNone.setText("暂无借款记录");
        }  else if (type == 10) {
            commonTitleTxt.setText("补贴记录");
            tvNone.setText("暂无补贴记录");
        }  else if (type == 11) {
            commonTitleTxt.setText("用章记录");
            tvNone.setText("暂无用章记录");
        }else if (14 == type) {
            commonTitleTxt.setText("入/离职记录");
            tvNone.setText("暂无入/离职记录");
        }else if (15 == type) {
            commonTitleTxt.setText("晋升记录");
            tvNone.setText("暂无晋升记录");
        }else if (16 == type) {
            commonTitleTxt.setText("回款记录");
            tvNone.setText("暂无回款记录");
        }else if (17 == type) {
            commonTitleTxt.setText("项目金额记录");
            tvNone.setText("暂无项目金额记录");
        }else if (18 == type) {
            commonTitleTxt.setText("入职记录");
            tvNone.setText("暂无入职记录");
        }else if (19 == type) {
            commonTitleTxt.setText("加班记录");
            tvNone.setText("暂无加班记录");
        }  else {
            commonTitleTxt.setText("请假记录");
            tvNone.setText("暂无请假记录");
        }
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                getCache();
                isEnd = false;
                currentPage = 1;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getCache();
    }

    private void getCache() {
        cacheList.clear();
        if (type == 7||type == 9||type == 10||type == 11) {
            cacheReimbursementList.clear();
            if (type == 7) {
                //报销
                cacheReimbursementList.addAll(XJson.getReimbursementDetailEntityCache(this,"", ReimbursementDetailEntity.class));
            }else if (type == 10) {
                //补贴
                cacheReimbursementList.addAll(XJson.getReimbursementDetailEntityCache(this,"subsidies", ReimbursementDetailEntity.class));
            }else if (type == 11) {
                //用章
                cacheReimbursementList.addAll(XJson.getReimbursementDetailEntityCache(this,"seal", ReimbursementDetailEntity.class));
            }else if (type == 14) {
                //离职
                cacheReimbursementList.addAll(XJson.getReimbursementDetailEntityCache(this,"resign", ReimbursementDetailEntity.class));
            }else if (type == 15) {
                //晋升
                cacheReimbursementList.addAll(XJson.getReimbursementDetailEntityCache(this,"upgrade", ReimbursementDetailEntity.class));
            }else{
                //借款
                cacheReimbursementList.addAll(XJson.getReimbursementDetailEntityCache(this,"money", ReimbursementDetailEntity.class));
            }
            for (int i = 0; i < cacheReimbursementList.size(); i++) {
                if (cacheReimbursementList.get(i).getCacheStatus() == 2) {
                    WorkNewEntity workNewEntity = new WorkNewEntity();
                    workNewEntity.setCacheStatus(2);
                    workNewEntity.setProjectName(cacheReimbursementList.get(i).getProjectName());
                    workNewEntity.setErrorRemark(cacheReimbursementList.get(i).getRemark());
                    workNewEntity.setErrorAmt(cacheReimbursementList.get(i).getAmt());
                    workNewEntity.setErrorGroupName(cacheReimbursementList.get(i).getGroupName());
                    workNewEntity.setErrorOrgName(cacheReimbursementList.get(i).getOrgName());
                    workNewEntity.setErrorOrgCode(cacheReimbursementList.get(i).getOrgCode());
                    if (type == 11) {
                        //用章
                        workNewEntity.setUseDetail(cacheReimbursementList.get(i).getUseDetail());
                        workNewEntity.setUseNum(cacheReimbursementList.get(i).getUseNum());
                        workNewEntity.setRemark(cacheReimbursementList.get(i).getRemark());
                        workNewEntity.setUseTime(cacheReimbursementList.get(i).getUseTime());
                        workNewEntity.setUseName(cacheReimbursementList.get(i).getProjectName());
                    }
                    cacheList.add(workNewEntity);
                }
            }
        }  else {
            //请假
            cacheHolidayList.clear();
            cacheHolidayList.addAll(XJson.getHolidayDetailEntityCache(this, HolidayDetailEntity.class));
            for (int i = 0; i < cacheHolidayList.size(); i++) {
                if (cacheHolidayList.get(i).getCacheStatus() == 2) {
                    WorkNewEntity workNewEntity = new WorkNewEntity();
                    workNewEntity.setCacheStatus(2);
                    workNewEntity.setProjectName(cacheHolidayList.get(i).getProjectName());
                    workNewEntity.setErrorLength(cacheHolidayList.get(i).getQingjiaLength());
                    workNewEntity.setErrorRemark(cacheHolidayList.get(i).getRemark());
                    workNewEntity.setErrorTime(cacheHolidayList.get(i).getStartTime() + " - " + cacheHolidayList.get(i).getEndTime());
                    cacheList.add(workNewEntity);
                }
            }
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        map.put("auditStatus", "1");// 为0是查询待办 为1是全部（待办加已办） 为空（或则其他数字时）时查询已办
        map.put("type", type+"");//3补卡4请假7报销记录  9借款记录10补贴11用章
        map.put("employeeCode", new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, ""));
//        employeeName 否
//        type 是 4 1新闻 2视频 3补卡 4请假
        String url="";
        if (type == 11) {
            url=Urls.selectUseZhangList;
        }else  if (type == 16) {
            url=Urls.selectItemAmtInfoList;
            map.put("groupCode", groupCode);
            map.put("amtType", 16+"");
        }else if (type == 14) {
            //离职晋升
            map.put("type", "14,18");
            url=Urls.selectKqMyWorkList;
        } else{
            url=Urls.selectKqMyWorkList;
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<WorkNewEntity>>>() {
        }.getType(), null, url, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<WorkNewEntity>>() {
            @Override
            public void onSuccess(List<WorkNewEntity> data) {

                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (smrRf == null) {
                    return;
                }
                int old = list.size();
                if (data != null && data.size() > 0) {
                    if (data.size() < pageSize) {
                        isEnd = true;
                    }
                    if (currentPage == 1 && cacheList.size() > 0) {
                        list.addAll(cacheList);
                        list.addAll(data);
                        adapter.notifyDataSetChanged();
                    }else{
                        list.addAll(data);
                        adapter.notifyItemRangeChanged(old, data.size());
                    }
                    smrRf.setVisibility(View.VISIBLE);
                } else {
                    isEnd = true;
                    if (currentPage == 1 && cacheList.size() > 0) {
                        list.addAll(cacheList);
                    }
                    if (list.size() == 0) {
                        adapter.setEmptyView(emptyView);
                    }else{
                        adapter.notifyDataSetChanged();
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();
            if (map.containsKey("ClockInAllRecordActivity_error_position")) {
                int position = Utils.changeNumber(map.get("ClockInAllRecordActivity_error_position"));
                if (type == 7) {
                    //报销
                    if (cacheReimbursementList.size() > position) {
                        XJson.setReimbursementDetailEntityCache(this, 1,"", cacheReimbursementList.get(position));
                        Intent intent = new Intent(this, ReimbursementActivity.class);
                        intent.putExtra("errorStatus", true);
                        intent.putExtra("data", cacheReimbursementList.get(position));
                        startActivity(intent);
                        smrRf.autoRefresh();
                    }
                }else if (type == 9) {
                    //借款
                    if (cacheReimbursementList.size() > position) {
                        XJson.setReimbursementDetailEntityCache(this, 1,"money", cacheReimbursementList.get(position));
                        Intent intent = new Intent(this, ReimbursementActivity.class);
                        intent.putExtra("errorStatus", true);
                        intent.putExtra("type", 9);
                        intent.putExtra("data", cacheReimbursementList.get(position));
                        startActivity(intent);
                        smrRf.autoRefresh();
                    }
                } else if (type == 10) {
                    //报销
                    if (cacheReimbursementList.size() > position) {
                        XJson.setReimbursementDetailEntityCache(this, 1,"subsidies", cacheReimbursementList.get(position));
                        Intent intent = new Intent(this, ReimbursementActivity.class);
                        intent.putExtra("errorStatus", true);
                        intent.putExtra("type", 10);
                        intent.putExtra("data", cacheReimbursementList.get(position));
                        startActivity(intent);
                        smrRf.autoRefresh();
                    }
                } else if (type == 11) {
                    //用章
                    if (cacheReimbursementList.size() > position) {
                        XJson.setReimbursementDetailEntityCache(this, 1,"seal", cacheReimbursementList.get(position));
                        Intent intent = new Intent(this, SealHomeActivity.class);
                        intent.putExtra("errorStatus", true);
                        intent.putExtra("type", 10);
                        intent.putExtra("data", cacheReimbursementList.get(position));
                        startActivity(intent);
                        smrRf.autoRefresh();
                    }
                }else if (type == 14) {
                    //离职
                    if (cacheReimbursementList.size() > position) {
                        XJson.setReimbursementDetailEntityCache(this, 1,"resign", cacheReimbursementList.get(position));
                        Intent intent = new Intent(this, SealHomeActivity.class);
                        intent.putExtra("errorStatus", true);
                        intent.putExtra("type", 10);
                        intent.putExtra("data", cacheReimbursementList.get(position));
                        startActivity(intent);
                        smrRf.autoRefresh();
                    }
                }else if (type == 15) {
                    //晋升
                    if (cacheReimbursementList.size() > position) {
                        XJson.setReimbursementDetailEntityCache(this, 1,"upgrade", cacheReimbursementList.get(position));
                        Intent intent = new Intent(this, SealHomeActivity.class);
                        intent.putExtra("errorStatus", true);
                        intent.putExtra("type", 10);
                        intent.putExtra("data", cacheReimbursementList.get(position));
                        startActivity(intent);
                        smrRf.autoRefresh();
                    }
                }else {
                    //请假
                    if (cacheHolidayList.size() > position) {
                        XJson.setHolidayDetailEntityCache(this, 1, cacheHolidayList.get(position));
                        Intent intent = new Intent(this, ClockInAskHolidayActivity.class);
                        intent.putExtra("errorStatus", true);
                        intent.putExtra("data", cacheHolidayList.get(position));
                        startActivity(intent);
                        smrRf.autoRefresh();
                    }
                }
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("RefreshClockInHolidayRecord")||msg.equals("RefreshReimbursementRecord")||msg.equals("RefreshSealRecord")||msg.equals("RefreshClockInManagerExamine")) {
                smrRf.autoRefresh();
            }
        }
    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @OnClick(R.id.common_title_back)
    public void onClick() {
        finish();
    }
}
